<template>
  <m-window-frame
    :title="$t(`创建${defaultTableName}`)"
    style="height: 100%"
    :okLoading="saveLoading"
    class="v-create-table-wizard"
    @cancel="handleCancel"
  >
    <div class="create-table-wizard-container">
      <AttrTips
        class="_main-title g-flex-0"
        :propertyGroupConfig="attrInfo"
        :type="''"
        background-image="statics/arch/theme/addtitlebg.png"
      ></AttrTips>
      <Step
        v-model="activeKey"
        :steps="steps"
        @stepValueChange="stepValueChange"
      ></Step>
    </div>
    <template v-slot:footer-right>
      <el-button
        size="small"
        :disabled="prevStepDisabled"
        @click="updateStep(-1)"
      >
        {{ "< " + $t("上一步") }}
      </el-button>
      <el-button
        size="small"
        :disabled="nextStepDisabled"
        @click="updateStep(1)"
      >
        {{ $t("下一步") + " >" }}
      </el-button>
      <el-button
        type="primary"
        size="small"
        :loading="saveLoading"
        :disabled="okDisabled"
        @click="handleSave"
      >
        {{ $t("完 成") }}
      </el-button>
      <el-button
        size="small"
        @click="handleCancel"
      >
        {{ $t("取 消") }}
      </el-button>
    </template>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import AttrTips from "@/common/attrTip/AttrTip.vue";
import Step, { type StepItem } from "../createTableWizard/Step.vue";
import { ref, computed, watch, markRaw } from "vue";
import { Params, CloseData } from "./index";
import { useRoute } from "vue-router";
import { ipcWindowUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import TreeSelect from "@/modules/model/modals/modelTreeSelect/components/TreeSelect.vue";
import { PropertyDataType } from "@/mdesign-lib/mdesign-app.umd.js";
import SelectTableOwner from "../createTableWizard/steps/SelectTableOwner.vue";
import ChartProperties from "../chartProperty/components/ChartProperties.vue";
import { toMap } from "@/util/common";

interface AttrInfo {
  name: string;
  description: string;
  icon: string;
}

const saveLoading = ref(false);
let projectId = "";
let stereotype = "";
let defaultTableName = "";
let defaultOwnerId = "";
let moreBtnCondition = "";
let moreBtnConditions: string[] = [];
let stepKeys: string[] = [];
const result = {
  style: {}
};

const route = useRoute();
watch(
  () => route.fullPath,
  () => {
    const routeQuery = route.query as unknown;
    const query = routeQuery as Params;
    projectId = query.projectId;
    stereotype = query.stereotype;
    defaultTableName = query.defaultTableName;
    defaultOwnerId = query.defaultOwnerId;
    stepKeys = query.stepKeys;
    moreBtnCondition = query.moreBtnCondition || "";
    moreBtnConditions = query.moreBtnConditions || [];
  },
  { immediate: true }
);

const allSteps: StepItem[] = [
  {
    key: "chooseOwner",
    name: "设置名称和所属包",
    description: "设置名称并选择一个包作为图的所有者",
    component: markRaw(SelectTableOwner),
    nextStepDisabled: true,
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          checkMethod: "validForecastTableOwner",
          modelId: stereotype
        },
        projectId
      },
      stereotype,
      multiple: false,
      showNodeLabel: true,
      defaultCurTab: "list",
      defaultSelectedId: defaultOwnerId,
      defaultTableName
    }
  },
  {
    key: "chooseActualOrganizationsAndActualPosts",
    name: "选择实际组织和实际岗位",
    description: "选择已经存在的实际组织和实际岗位",
    dataType: "InstanceIds",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          modelId: stereotype,
          checkMethod: null,
          moreBtnCondition
        },
        projectId
      },
      moreBtnConditions,
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseResource",
    name: "选择资源",
    description: "选择资源",
    dataType: "InstanceIds",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          modelId: stereotype,
          checkMethod: "validForecastTableRow"
        },
        projectId
      },
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseActualEnterprisePhase",
    name: "选择实际战略阶段",
    description: "选择实际战略阶段",
    dataType: "InstanceIds",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          checkMethod: "",
          modelId: stereotype,
          moreBtnCondition
        },
        projectId
      },
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseCapability",
    name: "选择能力",
    description: "选择能力",
    dataType: "InstanceIds",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          checkMethod: "",
          modelId: stereotype,
          moreBtnCondition
        },
        projectId
      },
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseActualProject",
    name: "选择实际项目",
    description: "选择实际项目",
    dataType: "InstanceIds",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          checkMethod: "",
          modelId: stereotype,
          moreBtnCondition
        },
        projectId
      },
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "setChatProperties",
    name: "设置图的属性",
    description: "指定图的显示样式",
    component: markRaw(ChartProperties),
    params: {
      diagramSts: stereotype
    }
  }
];
const allStepMap = toMap(allSteps, "key");
const steps = ref<StepItem[]>(stepKeys.map(key => allStepMap.get(key)).filter(Boolean) as StepItem[]);
const activeKey = ref("chooseOwner");

const activeStep = computed(() => {
  console.log("activeStep", activeKey.value);
  return steps.value.filter(step => step.key === activeKey.value)[0];
});

const attrInfo = computed<AttrInfo>(() => {
  return {
    name: activeStep.value.name as string,
    description: activeStep.value.description as string,
    icon: "statics/icons/attrTip/checkbox.svg"
  };
});

const currentStepIndex = computed(() => {
  return steps.value.findIndex(step => step.key === activeKey.value);
});

const prevStepDisabled = computed(() => {
  return currentStepIndex.value <= 0;
});

const nextStepDisabled = computed(() => {
  return currentStepIndex.value >= steps.value.length - 1 || steps.value[currentStepIndex.value].nextStepDisabled;
});

const okDisabled = computed(() => {
  return activeStep.value.nextStepDisabled;
});

const stepValueChange = (val: any, path: string[]) => {
  // console.log('stepValueChange', val, path);
  const from = path[0];
  if (from === "chooseOwner") {
    const key = path[path.length - 1];
    result[key] = val;
    if (key === "ownerId") {
      activeStep.value.nextStepDisabled = !val;
    }
  } else if (activeStep.value.dataType === "InstanceIds") {
    result["existModelIds"] = val;
  } else if (from === "setChatProperties") {
    const key = path[path.length - 1];
    result.style[key] = val;
  }
  console.log("result", result);
};

const updateStep = (num: number) => {
  activeKey.value = steps.value[currentStepIndex.value + num].key;
};

const handleSave = async () => {
  saveLoading.value = true;
  ipcWindowUtil.sendWindowChange({ success: true, result });
};

function handleclose(data: CloseData) {
  saveLoading.value = false;
  ipcWindowUtil.closeWindow(data);
  // emit('close', data);
  // remote.
}
function handleCancel() {
  handleclose({ success: false });
}
</script>
<style lang="scss">
.create-table-wizard-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
